<script setup>
import { onMounted, onUnmounted, defineProps, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

const props = defineProps({
  startAddress: {
    type: String,
    required: false,
  },
  endAddress: {
    type: String,
    required: false,
  },
  startLngLat: {
    type: Object, // { lon, lat }
    required: false,
  },
  endLngLat: {
    type: Object, // { lon, lat }
    required: false,
  },
  mapId: {
    type: String,
    required: true,
  }
});

console.log(`[DEBUG] MapContainer ${props.mapId} initial props:`, props.startAddress, props.endAddress);

let map = null;
let driving = null;
let geocoder = null;

const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "31f13ef0813081af58ce14580a1b0ec1",
  };
  AMapLoader.load({
    key: "222398eefd86001dd974d40a92253672",
    version: "2.0",
    plugins: ["AMap.Scale", "AMap.Driving", "AMap.Geocoder"], // 添加 Geocoder 插件
  })
    .then((AMap) => {
      map = new AMap.Map(props.mapId, { // 使用 props 中的 mapId
        showTraffic: false,
        mapStyle: "amap://styles/normal",
        zoom: 5,
        center: [111.28466, 30.701188],
      });

      driving = new AMap.Driving({
        policy: 0,
        map: map,
        hideMarkers: false,
        showTraffic: false,
      });

      geocoder = new AMap.Geocoder();

      // 初始加载时绘制路线
      drawRoute();
    })
    .catch((e) => {
      console.log(e);
    });
};

const drawRoute = () => {
  console.log(`[DEBUG] ${props.mapId} drawRoute called with:`, props);

  if (!driving || !geocoder) {
    console.log(`[DEBUG] ${props.mapId} drawRoute aborted: map services not ready.`);
    return;
  }

  const getStartPoint = () => {
    if (props.startLngLat && props.startLngLat.lon && props.startLngLat.lat) {
      return Promise.resolve([props.startLngLat.lon, props.startLngLat.lat]);
    }
    if (props.startAddress) {
      return geocodePromise(props.startAddress);
    }
    return Promise.reject(new Error('No start point provided.'));
  };

  const getEndPoint = () => {
    if (props.endLngLat && props.endLngLat.lon && props.endLngLat.lat) {
      return Promise.resolve([props.endLngLat.lon, props.endLngLat.lat]);
    }
    if (props.endAddress) {
      return geocodePromise(props.endAddress);
    }
    return Promise.reject(new Error('No end point provided.'));
  };

  const geocodePromise = (address) => {
    return new Promise((resolve, reject) => {
      geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          resolve(result.geocodes[0].location);
        } else {
          reject(new Error('地址解析失败: ' + address));
        }
      });
    });
  };

  console.log(`[DEBUG] ${props.mapId} Resolving route points...`);
  Promise.all([getStartPoint(), getEndPoint()])
    .then(([startPoint, endPoint]) => {
      console.log(`[DEBUG] ${props.mapId} Points resolved:`, { startPoint, endPoint });
      driving.search(startPoint, endPoint, (status, result) => {
        if (status === 'error') {
          console.error('路线规划失败:', result);
        }
      });
    })
    .catch(error => {
      console.error(`[DEBUG] ${props.mapId} Point resolving or route planning failed:`, error);
    });
};

onMounted(() => {
  initMap();
});

onUnmounted(() => {
  map?.destroy();
});

// 监听地址变化，重新绘制路线
watch([() => props.startAddress, () => props.endAddress], () => {
  console.log(`[DEBUG] ${props.mapId} Props changed, redrawing route.`);
  drawRoute();
});

</script>

<template>
  <div :id="mapId"></div>
</template>

<style scoped lang="less">
#container{
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 100%;
}
</style>